package top.wugy.blog.web;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import io.jsonwebtoken.Claims;
import top.wugy.blog.kits.BlogKit;
import top.wugy.blog.kits.Const;

/**
 * wugy on 2017/11/2 16:15
 */
public class AuthInterceptor implements Interceptor {

    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        String token = controller.getHeader(Const.TOKEN);
        if (StrKit.isBlank(token)) {
            controller.setAttr(Const.RES_CODE, Const.ERROR).setAttr(Const.RES_MSG, "没有访问权限");
            controller.renderJson();
            return;
        }
        Claims claims = BlogKit.getClaimsByToken(token);
        if (null == claims || BlogKit.isExpire(claims.getExpiration())) {
            controller.setAttr(Const.RES_CODE, Const.ERROR).setAttr(Const.RES_MSG, "token失效，请重新登录");
            controller.renderJson();
            return;
        }
        inv.invoke();
    }
}
